﻿#include "deviceprocess.h"


DeviceProcess::DeviceProcess()
{

}

DeviceProcess::~DeviceProcess()
{
    delete pDevice_Vector;
    delete pSelectedDevice;
}


void DeviceProcess::readConfig(QString config)
{
    // 将xml文件读取数据
    QFile file(config);

    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
      qDebug()<<"error";
    }

    if(NULL == pDevice_Vector)
    {
        pDevice_Vector = new QVector<Target*>;
    }

    pDevice_Vector->resize(DEVICES_CAPACITY);
    pDevice_Vector->clear();

    // 指定读取设备
    reader.setDevice(&file);

    while(!reader.atEnd())
    {
        // 读取下一个标签
        reader.readNext();
        // 解析内容
        if(reader.isStartElement())
        {
            // 解析
            if(QString("Device") == reader.name())
            {
                parseTarget();
            }
        }
    }

    return;
}


// 解析IP和PORT， 0 - Local， 1 - Remote
void DeviceProcess::parseSystem(Target* t, int index)
{
    while(1)
   {
        reader.readNext();

        if(QString("IP") == reader.name())
        {
            t->setIP(index, reader.readElementText());
            continue;
        }

        if(QString("Port") == reader.name())
        {
            t->setPort(index, reader.readElementText());
            continue;
        }
        if((QString("Local") == reader.name() || QString("Remote") ==reader.name()) && reader.isEndElement())
        {
            break;
        }
    }
    return;
}

void DeviceProcess::parseTarget()
{
        // 新建连接设备
        Target* target = new Target;
        while(1)
       {
            reader.readNext();

            if(QString("Name") == reader.name())
            {
                target->setDeviceName(reader.readElementText());
                continue;
            }

            if(QString("Local") == reader.name())
            {
                parseSystem(target, 0);
                continue;
            }

            if(QString("Remote") == reader.name())
            {
               parseSystem(target, 1);
               continue;
            }

            // 退出解析
            if(QString("Device") == reader.name() && reader.isEndElement())
            {
                break;
            }
        }
        pDevice_Vector->push_back(target);
        return;
}


QVector<Target*>* DeviceProcess::getAllDevices()
{
    return pDevice_Vector;
}


void DeviceProcess::setSelectedDevice(Target device)
{
    if(NULL == pSelectedDevice)
    {
        pSelectedDevice = new Target(device);
        return;
    }
    *pSelectedDevice = device;
    return;
}



Target* DeviceProcess::getSelectedDevice()
{
    return pSelectedDevice;
}
